package api

import (
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"regexp"
	"strconv"
	"time"
	"work-chess/dao"
	"work-chess/model"
	"work-chess/service"
)

var (
	reEmail = `[\w\.]+@\w+\.[a-z]{2,3}(\.[a-z]{2,3})?` //邮箱
)

type Context struct {
	*gin.Context
}

type UserInfo struct {
	UserName string `json:"user_name"`
	PassWord string `json:"pass_word"`
	Email    string `json:"email"`
}

func Register() gin.HandlerFunc {
	return func(con *gin.Context) {
		c := new(Context)
		c.Context = con
		userName := c.PostForm("username")
		passWord := c.PostForm("password")
		email := c.PostForm("email")
		if userName == "" || passWord == "" || email == "" {
			c.ReturnMessage(400, "信息未填写完")
			return
		}
		if !VerifyEmailFormat(email) {
			c.ReturnMessage(400, "邮箱格式错误")
			return
		}
		mailCenter := service.NewEmailCenter(&service.EmailConfig{
			ServerHost:   "smtp.163.com",      //邮箱服务器
			ServerPort:   25,                  //邮箱端口
			FromEmail:    "golightos@163.com", // 发送邮箱
			FromPassword: "HSSIXKSNNFBRQGKK",  //授权码
		})

		hash := sha256.New()
		hash.Write([]byte(email + time.Now().String()))
		sum := hash.Sum(nil)
		toStringsha256 := hex.EncodeToString(sum)

		user := new(UserInfo)
		user.UserName = userName
		user.PassWord = passWord
		user.Email = email
		marshaled, _ := json.Marshal(user)
		service.RedisDB.Set(toStringsha256, string(marshaled), time.Hour)
		url := "http://127.0.0.1:8081/user/register/verify?email_token=" + toStringsha256
		data := "golightos邮箱注册，点击以下链接完成认证：" + url
		err := mailCenter.AddToers(email).SetMessage("", "golightos注册", data).Send()
		if err != nil {
			c.ReturnMessage(500, "err")
			log.Println(err)
			return
		}
		c.ReturnMessage(200, "请前往邮箱查看")
	}
}

func EmailVerify() gin.HandlerFunc {
	return func(con *gin.Context) {
		c := new(Context)
		c.Context = con
		token := c.Query("email_token")
		fmt.Println("EmailVerify token=", token)
		val, ok := service.RedisVal(token)
		fmt.Println("test email val", val)
		if ok {
			u := new(UserInfo)
			json.Unmarshal([]byte(val), u)
			user, err := dao.AddUser(model.UserInfo{
				UserName: u.UserName,
				PassWord: u.PassWord,
				Email:    u.Email,
			})
			if err != nil {
				c.ReturnMessage(400, "注册失败")
				return
			}
			c.ReturnMessage(200, "id="+strconv.Itoa(int(user)))
			err = service.RedisDEL(token)
			if err != nil {
				log.Println(err)
				return
			}
			return
		}
		c.ReturnMessage(401, "err")
	}
}

func VerifyEmailFormat(email string) bool {
	//pattern := `\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*` //匹配电子邮箱
	pattern := `^[0-9a-z][_.0-9a-z-]{0,31}@([0-9a-z][0-9a-z-]{0,30}[0-9a-z]\.){1,4}[a-z]{2,4}$`
	reg := regexp.MustCompile(pattern)
	return reg.MatchString(email)
}

func (c *Context) ReturnMessage(code int, msg string) {
	status := false
	if code >= 200 && code <= 299 {
		status = true
	}
	c.JSON(code, gin.H{
		"status": status,
		"data":   msg,
	})
}
